<?php
namespace Yjsh\Controller;
use Common\Controller\AppframeController;
use Think\Cache\Driver\Redis;
use Yjsh\Model\GroupBuyGroupModel;
use Yjsh\Model\GroupBuyTempModel;
use Yjsh\Model\GroupBuyUserModel;
use Yjsh\Model\PayCallBackUrlModel;

/**
 * 首页
 */
class GroupbuyController extends AppframeController {

    private $page_size;
    // 成团模板
    private $GroupBuyTempModel;
    // 团模板商品
    private $GroupBuyProductModel;
    // 团购团队表
    private $GroupBuyGroupModel;
    // 团队成员表
    private $GroupBuyUserModel;
    // 支付等待时间
    private $pay_allow_time;

//    private $allow_users;

    function _initialize() {
        parent::_initialize();
        $this->page_size                = 10;
        $this->GroupBuyTempModel        = D("Yjsh/GroupBuyTemp");
        $this->GroupBuyProductModel     = D("Yjsh/GroupBuyProduct");
        $this->GroupBuyGroupModel       = D("Yjsh/GroupBuyGroup");
        $this->GroupBuyUserModel        = D("Yjsh/GroupBuyUser");
        $this->pay_allow_time           = 5 * 60; // 5分钟
//        $this->allow_users              = [981, 1646];
    }

    // 获取团购商品列表
    public function product_list()
    {
        // 成团模板id
        $t_id   = I('get.t_id', 1);
        $result = array('status' => 1);
        // 所有团模板
        $this->GroupBuyTempModel->order('created_at desc');
        if ($t_id > 0) {
            $groupBuyTemps = $this->GroupBuyTempModel->where(['id' => $t_id])->select();
        } else {
            $groupBuyTemps = $this->GroupBuyTempModel->limit(0)->select();
        }
        if ($groupBuyTemps) {
            $config = $this->get_config();
            $data   = array();
            foreach ($groupBuyTemps as $k => $v) {
                // 该团模板的所有商品
                $products = $this->GroupBuyProductModel
                    ->alias('gp')
                    ->join("__PRODUCT__ p on gp.p_id = p.id")
                    ->where(['gp.gbt_id' => $v['id'], 'gp.status' => 1])
                    ->order('gp.sort desc, gp.created_at desc')
                    ->limit(0)
                    ->field('gp.id as gbp_id, gp.p_id, gp.group_buy_price, gp.total_group_num, gp.left_group_num')
                    ->select();
                foreach ($products as $kp => $vp) {
                    $vp['group_name']    = $v['name'];
                    $vp['need_num']      = $v['need_num'];
                    $products[$kp]       = $vp;
                }
                $data = array_merge($products, $data);
            }
            $result['lists']            = $data;
            $result['img_base_url']     = $config ? $config['img_base_url'] : "";
        }
//        var_dump($result);
        $this->ajaxReturn($result);
    }

    // 创建拼团
    public function create_group()
    {
        $user_id    = I('get.user_id', 0);  // 用户id
        $gbp_id     = I('get.gbp_id', 0);   // 拼团商品id
        $result     = array();
//        if (!in_array($user_id, $this->allow_users)) {
//            $result['msg'] = '敬请期待';
//            $this->ajaxReturn($result);
//            exit;
//        }
        if ($user_id && $gbp_id) {
            // 团购商品信息
            $gbp_info = $this->GroupBuyProductModel->where(['id' => $gbp_id, 'status' => 1])->find();
            if ($gbp_info) {
                // 跨天，重置剩余商品数量
                $today_group    = $this->GroupBuyGroupModel->where(['gbp_id' => $gbp_id])->order('created_at desc')->find();
                $should_reset   = false;
                if ($today_group) {
                    if ($today_group['created_at'] < strtotime(date("Y-m-d ")) && $gbp_info['total_group_num'] != $gbp_info['left_group_num']) {
                        // 该商品今天没有开团，表示剩余商品数量没变过，并且总量和剩余不一致
                        $should_reset = true;
                    }
                }
                if ($should_reset) {
                    $re = $this->GroupBuyProductModel->where(['id' => $gbp_id])->save(['left_group_num' => $gbp_info['total_group_num']]);
                    if ($re) {
                        $gbp_info['left_group_num'] = $gbp_info['total_group_num'];
                    }
                }
                if ($gbp_info['left_group_num'] > 0) {
                    // 判断是否已有未结束的团
                    $has_grouping = $this->GroupBuyGroupModel
                        ->where(['gbp_id' => $gbp_id, 'own_uid' => $user_id, 'status' => ['in', [GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING, GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_WAIT_PAY]]])
                        ->field('id')
                        ->find();
                    if (!$has_grouping) {
                        $temp_info = $this->GroupBuyTempModel->where(['id' => $gbp_info['gbt_id']])->find();
                        if ($temp_info) {
                            // 时间限制
                            list($start_time, $end_time) = $this->get_gbg_time($temp_info['check_type'], $temp_info['check_time']);
                            if ($start_time < time() && time() < $end_time) {
                                // 先创建团，状态为待支付
                                $gbg_id = $this->insert_group_buy_group($user_id, $gbp_id, $temp_info['need_num'], GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_WAIT_PAY);
                                if ($gbg_id) {
                                    // 定时任务，5分钟将未支付订单状态改为支付失败
                                    $redis  = Redis::getinstance();
                                    $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_failed', ['type' => 'create', 'gbg_id' => $gbg_id]);
                                    $key    = "call_back|" . $url;
                                    $re     = $redis->get($key);
                                    if (!$re) {
                                        $redis->set($key, 1, $this->pay_allow_time);
                                    }

                                    // 创建支付回调操作数据
                                    $payCallBackUrlModel = D("Yjsh/PayCallBackUrl");
                                    $data = array(
                                        'user_id'       => $user_id,
                                        'amount'        => $gbp_info['group_buy_price'],
                                        'refund_amount' => $gbp_info['group_buy_price'],
                                        'order_type'    => PayCallBackUrlModel::ORDER_TYPE_GROUP_BUY,
                                        'can_refund'    => PayCallBackUrlModel::ORDER_CAN_REFUND_NO,
                                        'buy_info'      => json_encode(array(array('p_id' => $gbp_info['p_id'], 'reduce_stock' => 0))),
                                        'url'           => C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_call_back', ['type' => 'create', 'user_id' => $user_id, 'gbg_id' => $gbg_id]),
                                        'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                                        'params'        => '',
                                        'created_at'    => time(),
                                        'order_id'      => 0,
                                    );
                                    $pay_call_back_url_id = $payCallBackUrlModel->add($data);

                                    // 返回数据
                                    $result['status']               = 1;
                                    $result['gbg_id']               = $gbg_id;
                                    $result['pay_call_back_url_id'] = $pay_call_back_url_id;
                                } else {
                                    $result['msg'] = "系统忙碌，请稍后再试";
                                }
                            } else {
                                $result['msg'] = "超出拼团时间";
                            }
                        } else {
                            $result['msg'] = "参数错误";
                        }
                    } else {
                        $result['msg'] = "还有未成功的团";
                    }
                } else {
                    $result['msg'] = "已售罄";
                }
            } else {
                $result['msg'] = "参数错误";
            }
        } else {
            $result['msg'] = "参数错误";
        }
        $this->ajaxReturn($result);
    }

    // 加入拼团
    public function join_group()
    {
        $user_id    = I('get.user_id', 0);  // 用户id
        $gbg_id     = I('get.gbg_id', 0);   // 拼团团队id
        $result     = array();
        if ($user_id && $gbg_id) {
            // 团队信息
            $gbg_info = $this->GroupBuyGroupModel->where(['id' => $gbg_id])->find();
            if ($gbg_info) {
                if ($gbg_info['status'] != GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING) {
                    $result['msg'] = "来晚了，本团已结束";
                } elseif ($gbg_info['own_uid'] != $user_id) {
                    // 团购商品信息
                    $gbp_info = $this->GroupBuyProductModel->where(['id' => $gbg_info['gbp_id'], 'status' => 1])->find();
                    if ($gbp_info) {
                        if ($gbp_info['left_group_num'] > 0) {
                            // 团模板信息
                            $gbt_info = $this->GroupBuyTempModel->where(['id' => $gbp_info['gbt_id']])->find();
                            if ($gbt_info) {
                                // 时间限制
                                list($start_time, $end_time) = $this->get_gbg_time($gbt_info['check_type'], $gbt_info['check_time']);
                                if ($start_time < time() && time() < $end_time) {
                                    // 1 检查该团是不是满了
                                    $re = $this->GroupBuyGroupModel->where(['id' => $gbg_id, 'left_user_num' => ['GT', 0]])->save(['left_user_num' => ['exp', "left_user_num - 1"]]);
                                    if ($re) {
                                        // 插入拼团数据，状态设置为待支付
                                        $gbu_id = $this->insert_group_buy_user($user_id, $gbg_id, 0, GroupBuyUserModel::GROUP_BUY_USER_STATUS_WAIT_PAY);
                                        // 定时任务，5分钟将未支付订单状态改为支付失败
                                        $redis  = Redis::getinstance();
                                        $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_failed', ['type' => 'join', 'gbu_id' => $gbu_id]);
                                        $key    = "call_back|" . $url;
                                        $re1    = $redis->get($key);
                                        if (!$re1) {
                                            $redis->set($key, 1, $this->pay_allow_time);
                                        }
                                        // 确定减少库存量
                                        $gbus = $this->GroupBuyUserModel
                                            ->where(['gbg_id' => $gbg_id, 'status' => ['in', [GroupBuyUserModel::GROUP_BUY_USER_STATUS_WAIT_PAY, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS]]])
                                            ->field('id')
                                            ->select();
                                        $max_id = 0;
                                        foreach ($gbus as $v) {
                                            if ($v['id'] > $max_id) {
                                                $max_id = $v['id'];
                                            }
                                        }
                                        $reduce_stock = 0;
                                        if (count($gbus) >= $gbt_info['need_num']) {
                                            if ($max_id == $gbu_id) {
                                                $reduce_stock = $gbt_info['need_num'];
                                            }
                                        }
                                        // 创建支付回调操作数据
                                        $payCallBackUrlModel = D("Yjsh/PayCallBackUrl");
                                        $data = array(
                                            'user_id'       => $user_id,
                                            'amount'        => $gbp_info['group_buy_price'],
                                            'refund_amount' => $gbp_info['group_buy_price'],
                                            'order_type'    => PayCallBackUrlModel::ORDER_TYPE_GROUP_BUY,
                                            'can_refund'    => PayCallBackUrlModel::ORDER_CAN_REFUND_NO,
                                            'buy_info'      => json_encode(array(array('p_id' => $gbp_info['p_id'], 'reduce_stock' => $reduce_stock))),
                                            'url'           => C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_call_back', ['type' => 'join', 'user_id' => $user_id, 'gbg_id' => $gbg_id, 'gbu_id' => $gbu_id]),
                                            'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                                            'params'        => '',
                                            'created_at'    => time(),
                                            'order_id'      => 0,
                                        );
                                        $pay_call_back_url_id = $payCallBackUrlModel->add($data);

                                        $result['status'] = 1;
                                        $result['gbg_id'] = $gbg_id;
                                        $result['pay_call_back_url_id'] = $pay_call_back_url_id;
                                    } else {
                                        $result['msg'] = "手速太慢，该团已满~";
                                    }
                                } else {
                                    $result['msg'] = "超出拼团时间";
                                }
                            } else {
                                $result['msg'] = "参数错误";
                            }
                        } else {
                            $result['msg'] = "商品已售罄";
                        }
                    } else {
                        $result['msg'] = "参数错误";
                    }
                } else {
                    $result['msg'] = "已经在团队中";
                }
            } else {
                $result['msg'] = "参数错误";
            }
        } else {
            $result['msg'] = "参数错误";
        }
        $this->ajaxReturn($result);
    }

    // *****支付成功*****，回调的操作
    // 如果是开团，将拼团状态改为正在拼团，并且插入group_buy_user表,
    // 如果是加入团，将group_buy_user表订单状态改为已支付
    public function group_buy_pay_call_back() {
        $type       = I('get.type', '');    // 创建还是加入
        $user_id    = I('get.user_id', 0);  // 用户id
        $gbg_id     = I('get.gbg_id', 0);   // 拼团id
        $order_id   = I('get.order_id', 0); // 订单id
        $result     = array();
        if ($user_id && $gbg_id && $order_id && $type) {
            if ($type == 'create') {
                // 开团
                $gbg_info = $this->GroupBuyGroupModel->where(['own_uid' => $user_id, 'id' => $gbg_id])->find();
                if ($gbg_info) {
                    $gbp_info = $this->GroupBuyProductModel->where(['id' => $gbg_info['gbp_id']])->find();
                    if ($gbp_info) {
                        $gbt_info = $this->GroupBuyTempModel->where(['id' => $gbp_info['gbt_id']])->find();
                        if ($gbt_info) {
                            if ($gbg_info['status'] == GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_WAIT_PAY) {   // 等待支付结果
                                // 将状态改为已支付
                                $this->insert_group_buy_user($user_id, $gbg_id, $order_id, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS);
                                // 设置团的状态为正在拼团
                                $this->GroupBuyGroupModel->where(['id' => $gbg_id])->save(['status' => GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING]);
                                // 创建定时任务，将未成功的团中已支付的部分，退款处理
                                list($start_time, $end_time) = $this->get_gbg_time($gbt_info['check_type'], $gbt_info['check_time']);
                                if ($gbt_info['check_type'] == GroupBuyTempModel::GROUP_BUY_TEMP_CHECK_TYPE_DAY_TIME) {
                                    // 每天固定时间结束
                                    $gbg_task_id = 1;
                                } else {
                                    // 开团后N小时结束
                                    $gbg_task_id = $gbg_id;
                                }
                                // 设置任务，定时取消该团
                                $redis  = Redis::getinstance();
                                $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_task', ['type' => $gbt_info['check_type'], 'gbg_id' => $gbg_task_id]);
                                $key    = "call_back|" . $url;
                                $re     = $redis->get($key);
                                if (!$re) {
                                    $redis->set($key, 1, (int)($end_time - time()));
                                }
                                // 取消5分钟更改订单为支付失败的任务
                                $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_failed', ['type' => 'create', 'gbg_id' => $gbg_id]);
                                $key    = "call_back|" . $url;
                                $redis->del($key);
                                // 返回结果
                                $result['status']   = 1;
                                $result['msg']      = '支付成功';
                            } elseif ($gbg_info['status'] == GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_PAY_FAIL) { // 订单失效
                                // 将状态改为支付失败，但是order_id设置为不空，说明，订单失效，但是已支付过了
                                $this->insert_group_buy_user($user_id, $gbg_id, $order_id, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL);
                                $result['msg']      = "超出付款时间，订单失效";
                                $result['log_msg']  = "拼团订单已失效，但收到支付回调";
                            } else {
                                // 将状态改为支付失败，但是order_id设置为不空，说明，订单失效，但是已支付过了
                                $has_order = $this->GroupBuyUserModel->where(['order_id' => $order_id])->find();
                                if (!$has_order) {
                                    $this->insert_group_buy_user($user_id, $gbg_id, $order_id, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL);
                                }
                                $result['msg']      = '订单状态错误';
                                $result['log_msg']  = "拼团订单状态为已支付，再次收到支付回调";
                            }
                        } else {
                            $result['msg']     = "参数错误";
                            $result['log_msg'] = "未找到group_buy_temp_info";
                        }
                    } else {
                        $result['msg']      = "参数错误";
                        $result['log_msg']  = "未找到group_buy_product_info";
                    }
                } else {
                    $result['msg']      = "参数错误";
                    $result['log_msg']  = "未找到group_buy_group_info";
                }
            } else {
                // 加入团
                $gbu_id     = I('get.gbu_id', 0);   // group_buy_user 表id
                $gbu_info   = $this->GroupBuyUserModel->where(['user_id' => $user_id, 'gbg_id' => $gbg_id, 'id' => $gbu_id])->find();
                $gbg_info   = $this->GroupBuyGroupModel->where(['id' => $gbg_id])->find();
                if ($gbu_info && $gbg_info) {
                    $gbp_info = $this->GroupBuyProductModel->where(['id' => $gbg_info['gbp_id']])->find();
                    if ($gbp_info) {
                        $gbt_info = $this->GroupBuyTempModel->where(['id' => $gbp_info['gbt_id']])->find();
                        if ($gbt_info) {
                            if ($gbu_info['status'] == GroupBuyUserModel::GROUP_BUY_USER_STATUS_WAIT_PAY) {
                                // 当前状态是等待支付结果，将状态设置未已支付
                                $this->GroupBuyUserModel->where(['id' => $gbu_id])->save(['order_id' => $order_id, 'status' => GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS]);
                                // 取消5分钟将加入团订单失效的定时任务
                                $redis  = Redis::getinstance();
                                $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_pay_failed', ['type' => 'join', 'gbu_id' => $gbu_id]);
                                $key    = "call_back|" . $url;
                                $redis->del($key);
                                // 判断该团是不是成功了
                                $success_num = $this->GroupBuyUserModel->where(['gbg_id' => $gbg_id, 'status' => GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS])->count();
                                if ($success_num >= $gbt_info['need_num']) {
                                    // 剩余团购数量减1
                                    $re = $this->GroupBuyProductModel->where(['id' => $gbg_info['gbp_id'], 'status' => 1, 'left_group_num' => ['GT', 0]])->save(['left_group_num' => ['exp', "left_group_num - 1"]]);
                                    if ($re) {
                                        // 该订单支付成功后，该团就拼成了
                                        $this->GroupBuyGroupModel->where(['id' => $gbg_id])->save(['status' => GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_SUCCESS]);

                                        // 取消定时任务，已成功的团，取消定时检查
                                        if ($gbt_info['check_type'] != GroupBuyTempModel::GROUP_BUY_TEMP_CHECK_TYPE_DAY_TIME) {
                                            // 获取任务在redis中的key，并删除该key
                                            $url    = "http://" . C('DOMAIN_NAME') . U('Yjsh/Groupbuy/group_buy_task', ['type' => $gbt_info['check_type'], 'gbg_id' => $gbg_id]);
                                            $key    = "call_back|" . $url;
                                            $redis->del($key);
                                        }
                                        $result['status']   = 1;
                                        $result['msg']      = '拼团成功';
                                    } else {
                                        $result['msg']      = '手速太慢，都被别人抢走了';
                                        $result['log_msg']  = "最后一个加入团的人成功时，库存不足";
                                    }
                                } else {
                                    $result['status']   = 1;
                                    $result['msg']      = '成功加入拼团';
                                }
                            } elseif ($gbu_info['status'] == GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL) { // 订单失效
                                // 当前订单状态是已失效，将order_id设置为不空，说明，订单失效，但是已支付过了，退款时使用
                                $this->GroupBuyUserModel->where(['id' => $gbu_id])->save(['order_id' => $order_id]);
                                $result['msg']      = "超出付款时间，订单失效";
                                $result['log_msg']  = "加入团的订单超时失效，但收到支付回调";
                            } else {
                                // 当前订单状态是已支付或其他，再次收到支付回调，再写入一条数据，退款时使用
                                $has_order = $this->GroupBuyUserModel->where(['order_id' => $order_id])->find();
                                if (!$has_order) {
                                    $this->insert_group_buy_user($user_id, $gbg_id, $order_id, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL);
                                }
                                $result['msg']      = '支付成功';
                                $result['log_msg']  = "该加入团订单状态有误，再次收到支付回调";
                            }
                        } else {
                            $result['msg']      = "参数错误";
                            $result['log_msg']  = "未找到group_buy_temp_info";
                        }
                    } else {
                        $result['msg']      = "参数错误";
                        $result['log_msg']  = "未找到group_buy_product_info";
                    }
                } else {
                    $result['msg']      = "参数错误";
                    $result['log_msg']  = "未找到group_buy_user_info或者group_buy_group_info";
                }
            }
        } else {
            $result['msg'] = "参数错误";
        }
        // 记录错误log
        if (!isset($result['status'])) {
            writeFile("============ group_buy_pay_call_back_error " . $type . " ============ start");
            writeFile("type=" . $type . " user_id=" . $user_id . " gbg_id=" . $gbg_id . " order_id=" . $order_id . " gbu_id=" . $gbu_id);
            writeFile($result);
            writeFile("============ group_buy_pay_call_back_error =================== end");
        }
        // 清除本地log的字段，不返回给前端
        if (isset($result['log_msg'])) {
            unset($result['log_msg']);
        }
        $this->ajaxReturn($result);
    }

    // 定时任务，将未支付的拼团订单，状态改为支付失败
    public function group_buy_pay_failed()
    {
        $type   = I('get.type', '');
        $result = array('status' => -1);
        if ($type == 'create') {
            $gbg_id     = I('get.gbg_id', 0);
            $gbg_info   = $this->GroupBuyGroupModel->where(['id' => $gbg_id, 'status' => GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_WAIT_PAY])->find();
            if ($gbg_info) {
                // 将该团的支付状态，改为支付失败
                $result['status'] = 1;
                $this->GroupBuyGroupModel->where(['id' => $gbg_id])->save(['status' => GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_PAY_FAIL]);
            }
        } else {
            $gbu_id     = I('get.gbu_id', 0);
            $gbu_info   = $this->GroupBuyUserModel->where(['id' => $gbu_id, 'status' => GroupBuyUserModel::GROUP_BUY_USER_STATUS_WAIT_PAY])->find();
            if ($gbu_info) {
                $result['status'] = 1;
                // 将该加入团的订单，改为支付失败
                $this->GroupBuyUserModel->where(['id' => $gbu_id])->save(['status' => GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL]);
                // 将该团的 left_user_num 字段加1
                $this->GroupBuyGroupModel->where(['id' => $gbu_info['gbg_id']])->save(['left_user_num' => ['exp', "left_user_num + 1"]]);
            }
        }
        writeFile("======= group_buy_pay_failed ========= start");
        writeFile(I('get.'));
        writeFile("======= group_buy_pay_failed =========== end");
        $this->ajaxReturn($result);
    }

    // 查看开团详情
    public function get_group_buy_group_info()
    {
        $user_id    = I('get.user_id', 0);  // 用户id
        $gbg_id     = I('get.gbg_id', 0);   // 拼团团队id
        $result     = array();
        if ($user_id && $gbg_id) {
            // 团队信息
            $gbg_info = $this->GroupBuyGroupModel
                ->alias('gg')
                ->join('__USER__ u on gg.own_uid = u.id')
                ->where(['gg.id' => $gbg_id])
                ->field('gg.*, u.avatar_url')
                ->find();
            if ($gbg_info) {
                // 成员信息
                $team_members = $this->GroupBuyUserModel
                    ->alias('gu')
                    ->join("__USER__ u on gu.user_id = u.id")
                    ->where(['gu.gbg_id' => $gbg_id, 'gu.status' => ['in', [GroupBuyUserModel::GROUP_BUY_USER_STATUS_WAIT_PAY, GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS]]])
                    ->order("gu.created_at asc")
                    ->limit(0)
                    ->field('gu.*, u.nick_name, u.avatar_url')
                    ->select();

                $result['status']       = 1;
                $result['team_members'] = $team_members;
                $result['gbg_info']     = $gbg_info;

                // 开团进程
                $team_process = array();
                if ($gbg_info['created_at'] < strtotime(date("Y-m-d"))) {
                    // 不是当天的团
                    $team_process['status'] = 0;
                } else {
                    $team_process['status']         = 1; // 进度条是否结束
                    $team_process['is_shared']      = $this->is_group_shared($gbg_id); // 是否分享过
                    $team_process['is_success']     = $gbg_info['status'] == GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_SUCCESS;
                }
                $result['team_process'] = $team_process;

                // 商品信息
                $product_info = $this->GroupBuyProductModel
                    ->alias('gp')
                    ->join("__PRODUCT__ p on gp.p_id = p.id")
                    ->where(['gp.id' => $gbg_info['gbp_id']])
                    ->field("gp.id as gbp_id, gp.p_id, gp.group_buy_price, gp.total_group_num, gp.left_group_num")
                    ->find();
                $result['product_info'] = $product_info;

            } else {
                $result['msg'] = "参数错误2";
            }
        } else {
            $result['msg'] = "参数错误1";
        }
        $this->ajaxReturn($result);
    }

    // 设置团购已分享
    public function set_group_shared()
    {
        $gbg_id     = I('get.gbg_id', 0);   // 拼团团队id
        $result     = array();
        if ($gbg_id) {
            // 团队信息
            $gbg_info = $this->GroupBuyGroupModel->where(['id' => $gbg_id])->find();
            if ($gbg_info) {
                $this->set_group_shared_redis($gbg_id);
                $result['status'] = 1;
            } else {
                $result['msg'] = "参数错误";
            }
        } else {
            $result['msg'] = "参数错误";
        }
        $this->ajaxReturn($result);
    }

    // 定时任务，处理未成团的订单，并退款
    public function group_buy_task()
    {
        $type   = I("get.type", 0);
        $gbg_id = I('get.gbg_id', 0);
        $result = array('status' => -1);
        if ($type && $gbg_id) {
            if ($type == GroupBuyTempModel::GROUP_BUY_TEMP_CHECK_TYPE_DAY_TIME) {
                // 每天固定时间结束
                $where  = "((gg.status = " . GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING . ")";
                $where  .= " OR";
                $where  .= " (gu.order_id > 0 AND gu.status = " . GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL . "))";
                $where  .= " AND gu.order_id > 0 AND gg.created_at >= " . strtotime(date("Y-m-d"));
                // log
                $log_key = "============= group_buy_task_day_time ============= start";

            } else {
                // 开团后N小时结束
                $where  = "gg.id = " . $gbg_id . " AND";
                $where  .= " ((gg.status = " . GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING . ")";
                $where  .= " OR";
                $where  .= " (gu.order_id > 0 AND gu.status = " . GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL . "))";
                $where  .= " AND gu.order_id > 0 AND gg.created_at >= " . strtotime(date("Y-m-d"));
                // log
                $log_key = "============= group_buy_task_hour_" . $gbg_id . " ============= start";
            }
            $refund_lists = $this->GroupBuyGroupModel
                ->alias('gg')
                ->join("__GROUP_BUY_USER__ gu on gg.id = gu.gbg_id")
                ->where($where)
                ->limit(0)
                ->field('gg.id, gg.status, gu.order_id, gu.status as u_status, gu.id as gu_id')
                ->select();

            if ($refund_lists) {
                $orders = array_column($refund_lists, 'order_id');
                // 日志
                writeFile($log_key);
                writeFile($orders);
                $access_token = get_yjsh_access_token();
                if ($access_token) {
                    // 正式服
                    $url    = "https://yjsh.rixins.cn/admin/api/service/batchRefund";
                    // 本地测试
//                    $url    = "localhost:9010/api/service/batchRefund";

                    $data   = ['ids' => implode(',', $orders)];
                    $re     = curl_requestion($url, $data, 'POST', 60, ['access_token:' . $access_token]);
                    writeFile($re);
                    if ($re['status']) {
                        $re = json_decode($re['data'], true);
                        if ($re['code'] == 200 && !$re['data']) {
                            // 设置所有未成功的团的状态为已过期
                            $reset_group_lists  = array();
                            $reset_user_lists   = array();
                            foreach ($refund_lists as $k => $v) {
                                if ($v['status'] == GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING) {
                                    $reset_group_lists[] = $v['id'];
                                }
                                if ($v['u_status'] == GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_FAIL && $v['order_id'] > 0) {
                                    $reset_user_lists[] = $v['gu_id'];
                                }
                            }
                            // 设置未成团的团，状态为已失效
                            if ($reset_group_lists) {
                                writeFile("reset_group_lists lists");
                                writeFile($reset_group_lists);
                                $this->GroupBuyGroupModel->where(['id' => ['in', $reset_group_lists]])->save(['status' => GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_REFUND]);
                            }
                            // 设置已成团的但未能加入的用户，状态为已退款
                            if ($reset_user_lists) {
                                writeFile("reset_user_lists lists");
                                writeFile($reset_user_lists);
                                $this->GroupBuyUserModel->where(['id' => ['in', $reset_user_lists]])->save(['status' => GroupBuyUserModel::GROUP_BUY_USER_STATUS_REFUND]);
                            }
                            $result['status'] = 1;
                            writeFile($log_key . " success");
                        } else {
                            $result['status'] = -2;
                            writeFile($re['data']);
                            writeFile($log_key . " fail00");
                        }
                    } else {
                        $result['status'] = -3;
                        writeFile($log_key . " fail11");
                    }
                } else {
                    $result['status'] = -4;
                    writeFile($log_key . " fail22");
                }
            }
        }
        $this->ajaxReturn($result);
    }

    // 个人中心
    public function user_group_buy_lists()
    {
        $user_id    = I('get.user_id', 0);
        $position   = I('get.position', 0);
        $result     = array();
        if ($user_id) {
            // 检索条件
            $where = 'gu.user_id = ' . $user_id;
            if ($position == 1) {
                // 进行中
                $where .= " AND gg.created_at > " . strtotime(date("Y-m-d"));
                $where .= " AND gg.status = " . GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_ING;
                $where .= " AND gu.status = " . GroupBuyUserModel::GROUP_BUY_USER_STATUS_PAY_SUCCESS;
            } elseif ($position == 2) {
                // 已成团
                $where .= " AND gg.status = " . GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_SUCCESS;
                $where .= " AND gg.left_user_num = 0 ";
            } else {
                // 已取消
                $where .= " AND gg.status = " . GroupBuyGroupModel::GROUP_BUY_GROUP_STATUS_REFUND;
            }

            $config = $this->get_config();
            $count  = $this->GroupBuyUserModel
                ->alias('gu')
                ->join("__GROUP_BUY_GROUP__ gg on gu.gbg_id = gg.id", 'left')
                ->join("__GROUP_BUY_PRODUCT__ gp on gg.gbp_id = gp.id", 'left')
                ->join("__PRODUCT__ p on p.id = gp.p_id")
                ->where($where)
                ->count();
            $page   = $this->page($count, $this->page_size);
            $lists  = $this->GroupBuyUserModel
                ->alias('gu')
                ->join("__GROUP_BUY_GROUP__ gg on gu.gbg_id = gg.id", 'left')
                ->join("__GROUP_BUY_PRODUCT__ gp on gg.gbp_id = gp.id", 'left')
                ->join("__PRODUCT__ p on p.id = gp.p_id")
                ->where($where)
                ->limit($page->firstRow , $page->listRows)
                ->field('gu.status as u_status, gu.gbg_id as group_id, gu.created_at, gg.status as g_status, gp.group_buy_price, p.name, p.sale_price, p.market_price, p.pre_pic, gp.p_id as product_id')
                ->select();
            // 返回结果
            $result['status']       = 1;
            $result['img_base_url'] = $config ? $config['img_base_url'] : "";
            $result['total_page']   = ceil($count / $this->page_size);
            $result['lists']        = $lists;
        } else {
            $result['msg'] = "参数错误";
        }
        $this->ajaxReturn($result);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private function insert_group_buy_group($user_id, $gbp_id, $need_num, $status)
    {
        if ($user_id && $gbp_id) {
            $data = array(
                'gbp_id'        => $gbp_id,
                'own_uid'       => $user_id,
                'left_user_num' => $need_num - 1,
                'status'        => $status,
                'created_at'    => time(),
            );
            $gbg_id = $this->GroupBuyGroupModel->add($data);
            return $gbg_id;
        } else {
            return 0;
        }
    }

    private function insert_group_buy_user($user_id, $gbg_id, $order_id, $status)
    {
        if ($user_id && $gbg_id) {
            $data = array(
                'gbg_id'        => $gbg_id,
                'user_id'       => $user_id,
                'order_id'      => $order_id,
                'created_at'    => time(),
                'status'        => $status,
            );
            $re = $this->GroupBuyUserModel->add($data);
            return $re;
        } else {
            return 0;
        }
    }

    private function get_config()
    {
        $info = M('config')->where(['id' => 2])->find();
        if (!$info) {
            writeFile("GroupBuy get config error!!!!");
        }
        return $info ?: [];
    }

    // 设置该团已分享
    private function set_group_shared_redis($gbg_id)
    {
        $redis  = Redis::getinstance();
        $key    = "group_buy_share_" . $gbg_id;
        $re     = $redis->get($key);
        if (!$re) {
            $l_time = strtotime(date("Y-m-d ", strtotime("+1 day"))) - time();
            $redis->set($key, 1, (int)($l_time));
        }
    }

    private function is_group_shared($gbg_id)
    {
        $redis  = Redis::getinstance();
        $key    = "group_buy_share_" . $gbg_id;
        $re     = $redis->get($key);
        return $re ? true : false;
    }

    // 获取团购的开始和结束时间
    private function get_gbg_time($check_type, $check_time) {
        if ($check_type == GroupBuyTempModel::GROUP_BUY_TEMP_CHECK_TYPE_DAY_TIME) {
            // 每天固定时间结束
            $temp_end_time  = strtotime(date("Y-m-d")) + $check_time * 3600;
        } else {
            // 开团后N小时结束
            $temp_end_time  = time() + $check_time * 3600;
        }
        $config         = $this->get_config();
        $conf_end_time  = $config ? strtotime(date("Y-m-d ") . $config['group_end_time']) : strtotime(date("Y-m-d 23:00:00"));
        $start_time     = $config ? strtotime(date("Y-m-d ") . $config['group_start_time']) : strtotime(date("Y-m-d 01:00:00"));
        $finish_time    = min($temp_end_time, $conf_end_time);
        return [$start_time, $finish_time];
    }
}


